package com.hsqn.service.impl;

import com.hsqn.mapper.ElderlyMapper;
import com.hsqn.service.ElderlyService;
import hsqn.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.lang.module.Configuration;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ElderlyServiceImpl implements ElderlyService {

    @Autowired
    private ElderlyMapper elderlyMapper;

    @Override
    public Integer addElderly(Elderly elderly) {
        elderly.setCreatedTime(LocalDateTime.now());
        if(elderlyMapper.addElderly(elderly)>0){
            return Math.toIntExact(elderly.getId());
        }
        return null;
    }

    @Override
    public String updateElderly(Elderly elderly) {
      elderly.setUpdatedTime(LocalDateTime.now());
      if(elderlyMapper.updateElderly(elderly)>0){
          return "更新成功";
      }
      return "更新失败";

    }

    @Override
    public String addHealthRecord(HealthRecord healthRecord) {
        if(elderlyMapper.addHealthRecord(healthRecord)>0){
            return "添加成功";
        }
        return "添加失败";
    }

    @Override
    public String upHealthRecord(HealthRecord healthRecord) {
        if(elderlyMapper.upHealthRecord(healthRecord)>0){
            return "更新成功";
        }
        return "更新失败";
    }

    @Override
    public String upEvaluation(HealthRecord healthRecord) {
        healthRecord.setEvaluationTime(LocalDateTime.now());
        healthRecord.setUpdatedTime(LocalDateTime.now());
        if(elderlyMapper.upEvaluation(healthRecord)>0){
            return "更新成功";
        }
        return "更新失败";
    }

    @Override
    @Scheduled(cron = "0 0 1 * * ?")
    public void addAlarm() {
        List<HealthRecord> list= elderlyMapper.selectRecord();
        for (HealthRecord healthRecord : list){
           sendAlarm(healthRecord);
        }
    }

    @Override
    public void addLocationInfo() {
        //先获取所有老人信息
            List<Elderly> elderlyList = elderlyMapper.selectElderly();
        if (elderlyList.isEmpty()) {
            return;
        }
        // 提取所有老人的id（用于比对）
        List<Long> allElderlyIds = new ArrayList<>();
        for (Elderly elderly : elderlyList) {
            allElderlyIds.add(elderly.getId());
        }

        // 2. 获取location_info中已存在的elderly_id
        List<Long> existingLocationIds = elderlyMapper.selectLocationInfoIds();


        // 3. 处理删除：location_info中有，但elderly表中没有的id
        List<Long> needDeleteIds = new ArrayList<>();
        for (Long locationId : existingLocationIds) {
            boolean exists = false;
            for (Long elderlyId : allElderlyIds) {
                if (locationId.equals(elderlyId)) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                needDeleteIds.add(locationId);
            }
        }
        if (!needDeleteIds.isEmpty()) {
            elderlyMapper.batchDeleteLocation(needDeleteIds);
        }


        // 4. 处理新增：elderly表中有，但location_info中没有的id
        List<LocationInfo> needInsertList = new ArrayList<>();
        for (Elderly elderly : elderlyList) {
            Long elderlyId = elderly.getId();
            String address = elderly.getAddress();

            boolean exists = false;
            for (Long locationId : existingLocationIds) {
                if (elderlyId.equals(locationId)) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                LocationInfo location = new LocationInfo();
                location.setElderlyId(elderlyId);
                location.setLocationAddress(address); // 同步address
                needInsertList.add(location);
            }
        }
        if (!needInsertList.isEmpty()) {
            elderlyMapper.batchInsertLocation(needInsertList);
        }
    }

    @Override
    public void addAlarmInfo(AlarmInfo alarmInfo) {
        alarmInfo.setAlarmTime(LocalDateTime.now());
        elderlyMapper.addAlarmInfo(alarmInfo);
    }

    @Override
    public void upAlarmInfo(AlarmInfo alarmInfo) {
      elderlyMapper.upAlarmInfo(alarmInfo);
      Log log=new Log();
      log.setAlarmId(alarmInfo.getId());
      log.setElderlyId(alarmInfo.getElderlyId());
      log.setHandleUserId(alarmInfo.getHandleUserId());
      log.setHandleStatus(alarmInfo.getHandleStatus());
      log.setActionContent(alarmInfo.getAlarmContent());
      log.setCreateTime(LocalDateTime.now());
      //添加过程日志
      elderlyMapper.addLog(log);
    }


    private void sendAlarm(HealthRecord healthRecord){
         if(healthRecord.getBloodPressure()!=null&&!healthRecord.getBloodPressure().isEmpty()){
             String[] bpParts = healthRecord.getBloodPressure().split("/");
             if(bpParts.length==2){
                 int systolic = Integer.parseInt(bpParts[0]);
                 int diastolic = Integer.parseInt(bpParts[1]);
                 if (systolic > 130 || diastolic < 80){
                   createAlarm(healthRecord,"血压值异常:"+healthRecord.getBloodPressure());
                   return;
                 }
             }
         }else if(healthRecord.getBloodSugar()!=null){
             if(healthRecord.getBloodSugar().compareTo(new BigDecimal("7.0"))>=0||healthRecord.getBloodSugar().compareTo(new BigDecimal("3.9"))<=0){
                 createAlarm(healthRecord,"血糖值异常:"+healthRecord.getBloodSugar());
                 return;
             }
         }
    }
    public void createAlarm(HealthRecord healthRecord,String content){
        AlarmInfo alarmInfo = new AlarmInfo();
        alarmInfo.setElderlyId(healthRecord.getElderlyId());
        alarmInfo.setAlarmType(4);
        alarmInfo.setAlarmContent(content);
        alarmInfo.setAlarmTime(LocalDateTime.now());
        alarmInfo.setHandleStatus(0);
        elderlyMapper.addAlarm(alarmInfo);
    }
}
